package com.xiang.ad.service.impl;

import com.xiang.ad.constant.CommonStatus;
import com.xiang.ad.constant.Constants;
import com.xiang.ad.dao.AdPlanRepository;
import com.xiang.ad.dao.AdUserRepository;
import com.xiang.ad.entity.AdPlan;
import com.xiang.ad.entity.AdUser;
import com.xiang.ad.exception.AdException;
import com.xiang.ad.service.AdPlanService;
import com.xiang.ad.utils.CommonUtils;
import com.xiang.ad.vo.AdPlanGetRequest;
import com.xiang.ad.vo.AdPlanRequest;
import com.xiang.ad.vo.AdPlanResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created by xiang.
 * adPlanservice 的 crud的实现 创建、获取（批量）、更新、删除
 */
@Service
public class AdPlanServiceImpl implements AdPlanService {

    // user和plan的 dao
    private final AdUserRepository userRepository;
    private final AdPlanRepository planRepository;

    @Autowired
    public AdPlanServiceImpl(AdUserRepository userRepository,
                             AdPlanRepository planRepository) {
        this.userRepository = userRepository;
        this.planRepository = planRepository;
    }

    //创建adPlan
    @Override
    @Transactional
    public AdPlanResponse createAdPlan(AdPlanRequest request)
            throws AdException {
        // 参数校验
        if (!request.createValidate()) {
            throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }

        // 确保关联的 User对象 是存在的
        Optional<AdUser> adUser =
                userRepository.findById(request.getUserId());
        if (!adUser.isPresent()) {
            throw new AdException(Constants.ErrorMsg.CAN_NOT_FIND_RECORD);
        }

        //查看是否已经定义过同名adPlan
        AdPlan oldPlan = planRepository.findByUserIdAndPlanName(
                request.getUserId(), request.getPlanName()
        );
        if (oldPlan != null) {//触发 同名推广计划 异常
            throw new AdException(Constants.ErrorMsg.SAME_NAME_PLAN_ERROR);
        }

        //创建新的adPlan
        AdPlan newAdPlan = planRepository.save(
                new AdPlan(
                        request.getUserId(),
                        request.getPlanName(),
                        CommonUtils.parseStringDate(request.getStartDate()),
                        CommonUtils.parseStringDate(request.getEndDate())
                )
        );

        //
        return new AdPlanResponse(
                newAdPlan.getId(),
                newAdPlan.getPlanName());
    }

    //通过plan的ids 批量获取 plan
    @Override
    public List<AdPlan> getAdPlanByIds(AdPlanGetRequest request)
            throws AdException {

        //参数校验
        if (!request.validate()) {
            throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }
        //
        return planRepository.findAllByIdInAndUserId(
                request.getIds(), request.getUserId()
        );
    }

    //更新plan
    @Override
    @Transactional
    public AdPlanResponse updateAdPlan(AdPlanRequest request)
            throws AdException {

        //参数校验
        if (!request.updateValidate()) {
            throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }
        //查找plan  并且判断是否存在
        AdPlan plan = planRepository.findByIdAndUserId(
                request.getId(), request.getUserId()
        );
        if (plan == null) {
            throw new AdException(Constants.ErrorMsg.CAN_NOT_FIND_RECORD);
        }

        //参数非空的情况下，更新 name、startdate、enddate
        if (request.getPlanName() != null) {
            plan.setPlanName(request.getPlanName());
        }
        if (request.getStartDate() != null) {
            plan.setStartDate(
                    CommonUtils.parseStringDate(request.getStartDate())
            );
        }
        if (request.getEndDate() != null) {
            plan.setEndDate(
                    CommonUtils.parseStringDate(request.getEndDate())
            );
        }
        // 当前时间为 更新时间
        plan.setUpdateTime(new Date());
        // 保存plan
        plan = planRepository.save(plan);//save 即可以更新也可以保存，如果是更新必须带上主键，不然就会保存为一条新的记录

        return new AdPlanResponse(plan.getId(), plan.getPlanName());
    }

    //删除plan
    @Override
    @Transactional
    public void deleteAdPlan(AdPlanRequest request) throws AdException {

        //参数校验
        if (!request.deleteValidate()) {
            throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }

        //查询plan，查看是否存在
        AdPlan plan = planRepository.findByIdAndUserId(
                request.getId(), request.getUserId()
        );
        if (plan == null) {
            throw new AdException(Constants.ErrorMsg.CAN_NOT_FIND_RECORD);
        }

        //设状态为 不可用
        plan.setPlanStatus(CommonStatus.INVALID.getStatus());
        //当前时间为 更新时间
        plan.setUpdateTime(new Date());
        //保存plan
        planRepository.save(plan);
    }
}
